/**
 * Created by yunpeng on 2015/3/26.
 */
angular.module('starter.services', [])
    .factory('MainService',function(){
        return {
            all: function() {
                return null;
            },
            get: function() {
                // Simple index lookup
                return null;
            }
        }
    })
    .factory('LoginService',function($http){
        return {
            login: function(phone,password) {
                return $http({ //返回promise对象
                    method:'POST',
                    url:'/carrier/login',
                    data:{
                        username:phone,
                        password:password
                    }
                });
            },
            getCode: function(phone,type) {
                // Simple index lookup
                return $http({ //返回promise对象
                    method:'POST',
                    url:'/users/getCode',
                    data:{
                        username:phone,
                        type:type
                    }
                });
            },
            resetPass:function(phone,password) {
                return $http({ //返回promise对象
                    method:'POST',
                    url:'/users/resetPass',
                    data:{
                        username:phone,
                        password:password
                    }
                });
            },
            register:function(phone,password) {
                return $http({ //返回promise对象
                    method:'POST',
                    url:'/users/register',
                    data:{
                        username:phone,
                        password:password,
                        type:2
                    }
                });
            },
            bid:function(phone,company,myphone,price) {
                console.log(company);
                if(company){
                    return $http({ //返回promise对象
                        method:'POST',
                        url:'/users/Bid',
                        data:{
                            phone:phone,
                            company:company,
                            myphone:myphone,
                            price:price
                        }
                    });
                }else{
                    return $http({ //返回promise对象
                        method:'POST',
                        url:'/users/Bid',
                        data:{
                            phone:phone,
                            company:false,
                            myphone:myphone,
                            price:price
                        }
                    });
                }

            }
        }
    })
    .factory('TransferService',function($http){
        var date = new Date();
        var month = date.getMonth()+1;
        var day = date.getDate();
        if(month<10){
            month = '-0'+month;
        }else{
            month = '-'+month
        }
        if(day<10){
            day = '-0'+day;
        }else{
            day = '-'+day;
        }
        var dd = date.getFullYear()+month+day;
        var inforData = {
            type:1,//默认零散数量//2整板
            startCity:'',
            endCity:'',
            startCityId:'',
            endCityId:'',
            startTime:dd,
            endTime:dd,
            username:'',
            phone:Number(JSON.parse(localStorage.getItem('user')).phone),
            /*carbrand:[],
            carbrandid:'',*/
            carnum:[],
            draynum:[]
            //carnumid:'',
            //fileName:[]/*,
            //carnumber:[]//汽车数量*/
        };

        var carbrand={carbrand:[],carnums:[]};
        var carnums=[];

        var citys = [];
        var allcitys = [];
        var province = [];
        var currentcar = {brand:'品牌',bid:'',num:'型号',nid:'',carnumber:1,filepath:'',filename:'文件名'};
        /*var citys = */
        var currenttab = {state:false};
        var dray = {value:'12',num:0};
        return {
            getCitys:function($scope){
                $http({
                    method:'GET',
                    url:'/getCityList',
                    data:{
                    }
                }).success(function(data,status){
                    /*citys = data;*/
                    allcitys = data;
                    for(var i=0;i<data.length;i++){
                        if($.inArray(data[i].province,province)==-1){
                            province.push(data[i].province);
                        }

                    }
                    for(var i=0;i<data.length;i++){
                        if(province[0]==data[i].province){
                            citys.push(data[i]);
                        }
                    }
                    /*inforData.startCity=data[0].city;//设置默认城市
                    inforData.startCityId=data[0].id;
                    inforData.endCity=data[10].city;
                    inforData.endCityId=data[10].id;*/
                    inforData.startCity='北京市 朝阳';//设置默认城市
                    inforData.startCityId=20;
                    inforData.endCity='山东 济南';
                    inforData.endCityId=253;
                    $scope.inforData = inforData;
                    setTimeout(function(){//因为有冲突等会执行scope.$apply();
                        /*$scope.$apply(document.getElementById('wrapper'));*/
                        $scope.myScroll.refresh();        // Remember to refresh when contents are loaded (ie: on ajax completion)
                    },500);
                }).error(function(data,status){

                });
            },
            getCarbrands:function($scope){
                $http({
                    method:'GET',
                    url:'/getCarBrandList',
                    data:{
                    }
                }).success(function(data,status){
                    $scope.carbrands = data;
                    carbrand.carbrand = data;
                    setTimeout(function(){
                        $scope.myScroll.refresh();
                    },500);
                }).error(function(data,status){

                });
            },
            getCarNumList:function(id){
                $http({
                    method:'GET',
                    url:'/getCarNumList?id='+id,
                    data:{
                    }
                }).success(function(data,status){
                    carbrand.carnums = data;//车型列表

                }).error(function(data,status){

                });
            },
            savetransfer:function(){
                return $http({
                    method:'POST',
                    url:'/savetransfer',
                    data:{
                        inforData:inforData
                    }
                });
            },
            getCityList:function(){
              return citys;
            },
            getProvince:function(){
                return province;
            },
            getAllCitys:function(){
                return allcitys;
            },
            getInforData:function(){
                return inforData;
            },
            getCarbrandList:function(){
                return carbrand;
            },
            getCarNums:function(){
                return carnums;
            },
            getCurrentCar:function(){
                return currentcar;
            },
            resetCurrentCar:function(){
                currentcar = {brand:'品牌',bid:'',num:'型号',nid:'',carnumber:1,filepath:'',filename:'文件名',cropper:{}};
                return currentcar;
            },
            getCurrenttab:function(){
                return currenttab;
            },
            getDray:function(){
                return dray;
            },
            resetInforData:function(){
                citys = [];
                currenttab = {state:false};
                dray = {value:'12',num:0};
                inforData = {
                    type:1,//默认零散数量//2整板
                    startCity:'',
                    endCity:'',
                    startCityId:'',
                    endCityId:'',
                    startTime:dd,
                    endTime:dd,
                    username:'',
                    phone:Number(JSON.parse(localStorage.getItem('user')).phone),
                    carnum:[],
                    draynum:[]

                };
                return inforData;
            }

        }
    })
    .factory('AuthenticationService', function() {//记录登录认证状态
        var auth = {
            isLogged: false
        }
        return auth;
    })
    .factory('MyTransferService', function() {//记录登录认证状态
        var mytransferData = {datas:[]};

        return {
            getMytransferData:function(){
                return mytransferData;
            }
        }
    })
    .factory('TokenInterceptor', function ($q, $window, $location, AuthenticationService) {
        return {
            request: function (config) {
                config.headers = config.headers || {};
                if (localStorage.getItem('token')) {//$window.sessionStorage.token
                    config.headers.Authorization = 'Bearer ' + localStorage.getItem('token');//$window.sessionStorage.token;
                }
                return config;
            },

            requestError: function(rejection) {
                return $q.reject(rejection);
            },

            /* Set Authentication.isLogged to true if 200 received */
            response: function (response) {
                if (response != null && response.status == 200 && localStorage.getItem('token') && !AuthenticationService.isLogged) {
                    AuthenticationService.isLogged = true;
                }
                return response || $q.when(response);
            },

            /* Revoke client authentication if 401 is received */
            responseError: function(rejection) {
                if (rejection != null && rejection.status === 401 && (localStorage.getItem('token') || AuthenticationService.isLogged)) {
                    /*delete $window.sessionStorage.token;*/
                    /*localStorage.removeItem('token');
                    localStorage.removeItem('user');
                    AuthenticationService.isLogged = false;*/
                    $location.path("login");
                }

                return $q.reject(rejection);
            }
        };
    })
    .factory('CropperService', function() {//存放蹄片裁剪的参数，记录下来到服务器裁剪
        var cropperdata = [{
            scale1:'',
            scale2:'',
            width:'',
            height:'',
            filename:'',
            filepath:'文件名'
        }];

        return {
            getCropperdata:function(){
                return cropperdata;
            }
        }
    })
;